<template>
  <div class="map-chart-box">
    <div class="map-chart" ref="mapChart"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import mapData from './mapsdata/shaanxi.json'
import xianData from './mapsdata/xian.json'
import weinanData from './mapsdata/weinan.json'
import tcData from './mapsdata/tongchuan.json'
import ylData from './mapsdata/yulin.json'
import yaData from './mapsdata/yanan.json'
import akData from './mapsdata/ankang.json'
import hzData from './mapsdata/hanzhong.json'
import bjData from './mapsdata/baoji.json'
import slData from './mapsdata/shangluo.json'
import xyData from './mapsdata/xianyang.json'

// import zuanshiImage from '@/assets/imgs/zuanshi.png'
import zuanshiImage from '@/assets/imgs/statistics/pt2.png'
import { object } from 'vue-types'

const mapChart = ref(null)

const props = defineProps({
  cityType: Number,
  cityData: Object
})

const citySelect = ref(props.cityType)

watch(
  () => props.cityType,
  (newVal) => {
    handleChange(newVal)
  }
)

let chartInstance = null
onMounted(() => {
  initMap()
  // 监听窗口大小变化事件
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('resize', resizeChart)

  // 销毁ECharts实例
  if (chartInstance) {
    chartInstance.dispose()
  }
})

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize() // 调整ECharts实例大小
  }
}

const handleChange = (val) => {
  citySelect.value = val
  // 在更新前销毁旧的实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  initMap()
}

const initMap = async () => {
  // 检查是否已存在实例，如果不存在则初始化
  if (!chartInstance) {
    chartInstance = echarts.init(mapChart.value)
  }
  echarts.registerMap('shaanxi', { geoJSON: mapData })
  // switch (citySelect.value) {
  //   case 2:
  //     echarts.registerMap('shaanxi', { geoJSON: xianData })
  //     break
  //   case 3:
  //     echarts.registerMap('shaanxi', { geoJSON: tcData })
  //     break
  //   case 4:
  //     echarts.registerMap('shaanxi', { geoJSON: xyData })
  //     break
  //   case 5:
  //     echarts.registerMap('shaanxi', { geoJSON: bjData })
  //     break
  //   case 6:
  //     echarts.registerMap('shaanxi', { geoJSON: weinanData })
  //     break
  //   case 7:
  //     echarts.registerMap('shaanxi', { geoJSON: hzData })
  //     break
  //   case 8:
  //     echarts.registerMap('shaanxi', { geoJSON: akData })
  //     break
  //   case 9:
  //     echarts.registerMap('shaanxi', { geoJSON: slData })
  //     break
  //   case 10:
  //     echarts.registerMap('shaanxi', { geoJSON: ylData })
  //     break
  //   case 11:
  //     echarts.registerMap('shaanxi', { geoJSON: yaData })
  //     break
  //   default:
  //     echarts.registerMap('shaanxi', { geoJSON: mapData })
  //     break
  // }

  const transformData = (data) => {
    return Object.entries(data).map(([key, value]) => {
      // 替换分公司为市
      const label = key.replace('分公司', '市')
      const numValue = Number(value)
      return {
        label: label,
        value: numValue
      }
    })
  }

  const option = {
    backgroundColor: '#fff',
    tooltip: {
      show: citySelect.value == 1 ? true : false,
      // show: citySelect.value == 1 || citySelect.value == 12 ? true : false,
      trigger: 'item', // 鼠标悬停触发
      formatter: function (params) {
        const cityName = params.name
        const projectSumData = transformData(props.cityData.projectSumByRegion)
        const projectAmountData = transformData(props.cityData.projectAmountSumByRegion)
        const cityInfoNumber = projectSumData.find((item) => item.label === cityName)?.value || 0
        const cityInfoMoney = projectAmountData.find((item) => item.label === cityName)?.value || 0
        return `
  <div style="min-width:100px;">
${cityName}<br/>项目总数(个)：${cityInfoNumber}<br/>总合同额(万)：${cityInfoMoney}</div>`
      }
    },

    geo: {
      show: true,
      map: 'shaanxi',
      emphasis: {
        normal: {
          show: false
        },
        label: {
          show: false
        }
      },

      roam: false,
      itemStyle: {
        areaColor: {
          type: 'linear',
          x: 0, // 渐变方向（0度为水平，90度为垂直）
          y: 0,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(235,244,254,1)' // 0% 处的颜色
            },
            {
              offset: 1,
              color: 'rgba(230,242,255,1)' // 100% 处的颜色
            }
          ],
          global: false // 是否全局坐标系，默认为false
        },
        borderWidth: 2,
        borderColor: '#0958D9'
        // shadowColor: 'rgba(46,124,246,0.2)',
        // shadowBlur: 150
      }
    },
    series: [
      {
        type: 'map',
        map: 'shaanxi',
        geoIndex: 1,
        aspectScale: 0.75, //长宽比
        showLegendSymbol: false, // 存在legend时显示
        label: {
          show: true,
          color: '#0958D9',
          rich: {
            a: {
              height: 20,
              align: 'center'
            },
            b: {
              height: 20,
              align: 'center',
              backgroundColor: {
                image: zuanshiImage
              }
            }
          },
          formatter: function (params) {
            return '{a|}\n{b|}' + params.name
          },
          label: {
            emphasis: {
              color: 'rgb(183,185,14)'
            }
          }
        },
        roam: false,
        itemStyle: {
          areaColor: {
            type: 'linear',
            x: 0, // 渐变方向（0度为水平，90度为垂直）
            y: 0,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(235,244,254,1)' // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(230,242,255,1)' // 100% 处的颜色
              }
            ],
            global: false // 是否全局坐标系，默认为false
          },
          borderColor: 'rgba(9, 88, 217, 0.2)',
          borderWidth: 1,
          itemStyle: {
            areaColor: {
              type: 'linear',
              x: 0,
              y: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(235,244,254,1)'
                },
                {
                  offset: 1,
                  color: 'rgba(230,242,255,1)'
                }
              ]
            }
          }
        }
      }
    ]
  }
  chartInstance.setOption(option, true)
}
</script>

<style lang="scss" scoped>
.map-chart-box {
  position: relative;
  height: 600px;
}

.map-chart {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
</style>